package com.sjb.cp.api.aliyun.sub;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.sjb.cp.api.aliyun.model.CreateOutPaintingTaskRequest;
import com.sjb.cp.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.sjb.cp.api.aliyun.model.GetOutPaintingResponse;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.exception.ThrowUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @Author:sjb
 * @CreateTime:2025-02-11
 * @Description: 阿里云AI-API
 * @Version：1.0
 */
@Component
@Slf4j
public class AliYunAiApi {

    @Value("${aliyah.apiKey}")
    private String aliyahApiKey;

    /**
     * 创建任务URL
     */
    private static final String CREATE_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/image2image/out-painting";
    /**
     * 查询创建任务URL
     */
    private static final String QUERY_TASK_URL = "https://dashscope.aliyuncs.com/api/v1/tasks/%s";


    /**
     * 创建编辑图片任务
     *
     * @param createOutPaintingTaskRequest
     * @return
     */
    public CreateOutPaintingTaskResponse createOutPaintingTask(CreateOutPaintingTaskRequest createOutPaintingTaskRequest) {
        ThrowUtils.throwIf(createOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR, "编辑图片参数为空");
        // 1、组装请求头&请求体
        HttpRequest httpRequest = HttpRequest.post(CREATE_TASK_URL)
                .header(Header.AUTHORIZATION, "Bearer " + aliyahApiKey)
                .header("X-DashScope-Async", "enable")
                .header(Header.CONTENT_TYPE, "application/json")
                .body(JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        // 2、发起请求
        HttpResponse response = httpRequest.execute();
        // 3、处理请求
        boolean responseOk = response.isOk();
        if (!responseOk) {
            log.error("请求扩图失败,响应为：{}", response);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求扩图失败");
        }
        String body = response.body();
        log.info("编辑图片响应体为：{}",body);
        CreateOutPaintingTaskResponse outPaintingTaskResponse = JSONUtil.toBean(body, CreateOutPaintingTaskResponse.class);
        String code = outPaintingTaskResponse.getCode();
        String message = outPaintingTaskResponse.getMessage();
        if (!StrUtil.isEmpty(code)) {
            log.error("请求扩图失败,code:{},message:{}", code, message);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请求扩图失败");
        }
        return outPaintingTaskResponse;
    }

    /**
     * 查询图片编辑结果信息
     *
     * @param taskId 任务ID
     * @return
     */
    public GetOutPaintingResponse getOutPaintingStatus(String taskId) {
        HttpRequest httpRequest = HttpRequest.get(String.format(QUERY_TASK_URL, taskId))
                .header(Header.AUTHORIZATION, "Bearer " + aliyahApiKey);
        HttpResponse response = httpRequest.execute();
        boolean responseOk = response.isOk();
        if (!responseOk) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取任务失败");
        }
        log.info("查询图片编辑响应任务的响应体为：{}",response.body());
        GetOutPaintingResponse getOutPaintingResponse = JSONUtil.toBean(response.body(), GetOutPaintingResponse.class);
        log.info("查询图片编辑响应任务的ID为：{}",getOutPaintingResponse);
        return getOutPaintingResponse;
    }

}
